package c.mars.tower_of_hanoi.menu;

// FIXME: This class currently isn't working, because of crash in texture loading 
// (maybe need to fix shaders, cause bitmap in loadBitmap wasn't null on my device)

import c.mars.tower_of_hanoi.R;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLUtils;
import android.util.Log;

public class TexturedSquareButton {

	private final String TAG = getClass().getName();
	
//	Shaders
   public static final String vertexShaderCode =
       "uniform mat4 uMVPMatrix;" +
       "attribute vec4 vPosition;" +
       "attribute vec2 a_texCoord;" +
       "varying vec2 v_texCoord;" +
       "void main() {" +
       "  gl_Position = uMVPMatrix * vPosition;" +
       "  v_texCoord = a_texCoord;" +
       "}";

   public static final String fragmentShaderCode =
       "precision mediump float;" +
       "varying vec2 v_texCoord;" +
       "uniform sampler2D s_texture;" +
       "void main() {" +
       "  gl_FragColor = texture2D( s_texture, v_texCoord );" +
       "}";
    
    private FloatBuffer vertexBuffer;
    private final ShortBuffer drawListBuffer;
    private FloatBuffer textureBuffer;
    private final int mProgram;
    private int mPositionHandle;
    private int mTextureHandle;
    private int mMVPMatrixHandle;
	
//  Number of coordinates per vertex in this array
    static final int COORDS_PER_VERTEX = 3;
    static float vertices[] = {
        -0.5f,  0.5f, 0.0f,   // top left
        -0.5f, -0.5f, 0.0f,   // bottom left
         0.5f, -0.5f, 0.0f,   // bottom right
         0.5f,  0.5f, 0.0f }; // top right
//	This button will use only one texture
	private int[] textures = new int[1];
    private final short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices
    
//  Texture coordinates
    private float texture[] = {    		
    		// Mapping coordinates for the vertices
    		0.0f, 1.0f,		// top left		(V2)
    		0.0f, 0.0f,		// bottom left	(V1)
    		1.0f, 1.0f,		// top right	(V4)
    		1.0f, 0.0f		// bottom right	(V3)
    };

    private final int vertexStride = COORDS_PER_VERTEX * 4; // 4 bytes per vertex		
    
	public TexturedSquareButton() {
		// initialize vertex byte buffer for shape coordinates
        ByteBuffer bb = ByteBuffer.allocateDirect(
        // (# of coordinate values * 4 bytes per float)
                vertices.length * 4);
        bb.order(ByteOrder.nativeOrder());
        vertexBuffer = bb.asFloatBuffer();
        vertexBuffer.put(vertices);
        vertexBuffer.position(0);

        // initialize byte buffer for the draw list
        ByteBuffer dlb = ByteBuffer.allocateDirect(
                // (# of coordinate values * 2 bytes per short)
                drawOrder.length * 2);
        dlb.order(ByteOrder.nativeOrder());
        drawListBuffer = dlb.asShortBuffer();
        drawListBuffer.put(drawOrder);
        drawListBuffer.position(0);

        //
        ByteBuffer byteBuf = ByteBuffer.allocateDirect(texture.length * 4);
		byteBuf.order(ByteOrder.nativeOrder());
		textureBuffer = byteBuf.asFloatBuffer();
		textureBuffer.put(texture);
		textureBuffer.position(0);

        // prepare shaders and OpenGL program
        int vertexShader = MenuRenderer.loadShader(
                GLES20.GL_VERTEX_SHADER,
                vertexShaderCode);
        int fragmentShader = MenuRenderer.loadShader(
                GLES20.GL_FRAGMENT_SHADER,
                fragmentShaderCode);

        mProgram = GLES20.glCreateProgram();             // create empty OpenGL Program
        GLES20.glAttachShader(mProgram, vertexShader);   // add the vertex shader to program
        GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
        GLES20.glLinkProgram(mProgram);                  // create OpenGL program executables
	}
	
//	Loading texture from resource
	public void loadGLTexture(GL10 gl, Context context) {
		// loading texture
		Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.menuitem3);

		Log.w(TAG, String.format("loadGLTexture: bitmap is %s", (bitmap == null) ? "null" : "loaded" ));
		
		// generate one texture pointer
		GLES20.glGenTextures(1, textures, 0);
		// ...and bind it to our array
		GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]);
		
		// create nearest filtered texture
		GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
		GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
		
		GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); 
		GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
		
		// Use Android GLUtils to specify a two-dimensional texture image from our bitmap 
		GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
		
		// Clean up
		bitmap.recycle();
	}

	public void draw(float[] mvpMatrix) {
		// Add program to OpenGL environment
        GLES20.glUseProgram(mProgram);

        // get handle to vertex shader's vPosition member
        mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");

        // Enable a handle to the triangle vertices
        GLES20.glEnableVertexAttribArray(mPositionHandle);

        // Prepare the triangle coordinate data
        GLES20.glVertexAttribPointer(
                mPositionHandle, COORDS_PER_VERTEX,
                GLES20.GL_FLOAT, false,
                vertexStride, vertexBuffer);
        
//     // Get handle to texture coordinates location
        mTextureHandle = GLES20.glGetAttribLocation(mProgram, "a_texCoord" );
//	    
	    Log.w(TAG, String.format("loadGLTexture: mTextureHandle is %d", mTextureHandle)); 
//	    
//	    // Enable generic vertex attribute array
	    GLES20.glEnableVertexAttribArray ( mTextureHandle );
//	    
//	    // Prepare the texture coordinates
	    GLES20.glVertexAttribPointer ( mTextureHandle, 2, GLES20.GL_FLOAT,
                false, 
                0, textureBuffer);
//        
//        // get handle to shape's transformation matrix
        mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
        MenuRenderer.checkGlError("glGetUniformLocation");
//
//        // Apply the projection and view transformation
        GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);
        MenuRenderer.checkGlError("glUniformMatrix4fv");
//
        int mTextureSample = GLES20.glGetUniformLocation (mProgram, "s_texture" );
//        
//        // Set the sampler texture unit to 0, where we have saved the texture.
        GLES20.glUniform1i ( mTextureSample, 0);
//        
//        // Draw the square
        GLES20.glDrawElements(
                GLES20.GL_TRIANGLES, drawOrder.length,
                GLES20.GL_UNSIGNED_SHORT, drawListBuffer);
//
//        // Disable vertex array
        GLES20.glDisableVertexAttribArray(mPositionHandle);
	}
}
